import 'package:flutter/material.dart';

class BackupSettingsScreen extends StatefulWidget {
  const BackupSettingsScreen({super.key});

  @override
  State<BackupSettingsScreen> createState() => _BackupSettingsScreenState();
}

class _BackupSettingsScreenState extends State<BackupSettingsScreen> {
  bool _isAutoBackupEnabled = false;
  String _backupFrequency = '每周';
  bool _isBackupInProgress = false;
  DateTime? _lastBackupTime;
  
  // 备份频率选项
  final List<String> _frequencyOptions = ['每天', '每周', '每月'];
  
  @override
  void initState() {
    super.initState();
    // 模拟加载备份设置
    _loadBackupSettings();
  }
  
  void _loadBackupSettings() {
    // 模拟从本地存储加载备份设置
    // 实际应用中，这里应该从SharedPreferences或其他存储中读取
    setState(() {
      _isAutoBackupEnabled = true;
      _backupFrequency = '每周';
      _lastBackupTime = DateTime.now().subtract(const Duration(days: 3));
    });
  }
  
  void _saveBackupSettings() {
    // 模拟保存备份设置到本地存储
    // 实际应用中，这里应该保存到SharedPreferences或其他存储中
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('备份设置已保存'))
    );
  }
  
  void _performBackup() async {
    setState(() {
      _isBackupInProgress = true;
    });
    
    // 模拟备份过程
    await Future.delayed(const Duration(seconds: 2));
    
    setState(() {
      _isBackupInProgress = false;
      _lastBackupTime = DateTime.now();
    });
    
    // 显示备份成功提示
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('备份成功'))
      );
    }
  }
  
  void _restoreFromBackup() async {
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('从备份恢复'),
        content: const Text('从备份恢复将覆盖当前数据，确定要继续吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );
    
    if (confirmed != true) return;
    
    setState(() {
      _isBackupInProgress = true;
    });
    
    // 模拟恢复过程
    await Future.delayed(const Duration(seconds: 3));
    
    setState(() {
      _isBackupInProgress = false;
    });
    
    // 显示恢复成功提示
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('恢复成功'))
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('备份设置'),
        centerTitle: true,
      ),
      body: Stack(
        children: [
          ListView(
            padding: const EdgeInsets.all(16),
            children: [
              // 自动备份设置
              Card(
                margin: const EdgeInsets.only(bottom: 16),
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '自动备份',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      SwitchListTile(
                        title: const Text('启用自动备份'),
                        subtitle: const Text('定期自动备份您的数据'),
                        value: _isAutoBackupEnabled,
                        onChanged: (value) {
                          setState(() {
                            _isAutoBackupEnabled = value;
                          });
                        },
                      ),
                      if (_isAutoBackupEnabled) ...[  
                        const Divider(),
                        ListTile(
                          title: const Text('备份频率'),
                          trailing: DropdownButton<String>(
                            value: _backupFrequency,
                            onChanged: (value) {
                              if (value != null) {
                                setState(() {
                                  _backupFrequency = value;
                                });
                              }
                            },
                            items: _frequencyOptions.map((option) {
                              return DropdownMenuItem(
                                value: option,
                                child: Text(option),
                              );
                            }).toList(),
                          ),
                        ),
                      ],
                      const SizedBox(height: 8),
                      Align(
                        alignment: Alignment.centerRight,
                        child: TextButton(
                          onPressed: _saveBackupSettings,
                          child: const Text('保存设置'),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              
              // 手动备份和恢复
              Card(
                margin: const EdgeInsets.only(bottom: 16),
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '手动备份与恢复',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      if (_lastBackupTime != null)
                        Padding(
                          padding: const EdgeInsets.only(bottom: 16),
                          child: Text(
                            '上次备份时间: ${_formatDateTime(_lastBackupTime!)}',
                            style: TextStyle(
                              color: Colors.grey.shade600,
                            ),
                          ),
                        ),
                      Row(
                        children: [
                          Expanded(
                            child: ElevatedButton.icon(
                              onPressed: _isBackupInProgress ? null : _performBackup,
                              icon: const Icon(Icons.backup),
                              label: const Text('立即备份'),
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: OutlinedButton.icon(
                              onPressed: _isBackupInProgress ? null : _restoreFromBackup,
                              icon: const Icon(Icons.restore),
                              label: const Text('从备份恢复'),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              
              // 备份说明
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '关于备份',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      const Text(
                        '备份将保存您的所有数据，包括单词、笔记、题目和作文素材等。备份文件存储在本地，您可以随时恢复数据。',
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '注意：恢复数据将覆盖当前所有数据，请谨慎操作。',
                        style: TextStyle(
                          color: Theme.of(context).colorScheme.error,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          
          // 加载指示器
          if (_isBackupInProgress)
            Container(
              color: Colors.black.withOpacity(0.3),
              child: const Center(
                child: Card(
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        CircularProgressIndicator(),
                        SizedBox(height: 16),
                        Text('正在处理，请稍候...'),
                      ],
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
  
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}